
#ifndef _THREADSPIDER_H_
#define _THREADSPIDER_H_

#define BOOST_SIGNALS_NO_DEPRECATION_WARNING

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/signal.hpp>
#include <string>

#include "WebKit.h"
#include "WebPage.h"

#define LIMIT_CONNECT_SIZE 200

using namespace SpiderWebKitClient;

class WKRequest {
    public:
    WKRequest(std::string url, boost::function< void (WebPage *)> cb, int level);
    ~WKRequest();

    void start();

    void run();

    bool isAlive();

    private:
    std::string m_url;
    boost::signal< void (WebPage *)> m_sig;
    int m_level;
    bool m_alive;
};

class ThreadSpider {
    public:

    template<typename T>
    WKRequest *createRequest(std::string url, T *obj, void (T::*parseCallback)(WebPage *), int level = 100)
    {
        boost::mutex::scoped_lock lock(m_requestMutex);
        WKRequest *req = new WKRequest(url, boost::bind(parseCallback, obj, _1), level);
        m_requests.push_back(req);
        return req;
    }

    void destroyRequest(WKRequest* request);

    void start();

    void run();

    long requestCount();

    private:
    std::list<WKRequest*> m_requests;
    std::list<WKRequest*> m_aliveRequests;
    std::list<WKRequest*> m_diedRequests;
    boost::mutex m_requestMutex;
};

#endif

